import os
import json

class ConfigManager:
    _instance = None  # 单例实例

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls, *args, **kwargs)
            cls._instance._init_config()
        return cls._instance

    def _init_config(self):
        self.config_path = "config.json"  # 配置文件路径
        # 默认配置（无文件时使用）
        self.default_config = {
            "send_settings": {  # 弹幕发送设置
                "room_ids": "",       # 发送目标房间（逗号分隔）
                "danmu_messages": [], # 弹幕内容列表
                "min_interval": 10,   # 最小发送间隔（秒）
                "max_interval": 30    # 最大发送间隔（秒）
            },
            "listener_settings": {  # 礼物监听设置
                "listen_room_ids": [],  # 监听房间列表
                "push_target_room": ""  # 盈亏推送目标房间
            },
            "query_settings": {  # 查询监听设置
                "enabled": False,
                "query_lister_text": ""  # 查询监听文本
            },
            "comprehensive_settings": {  # 综合设置
                "thank_for_follow": {  # 感谢关注
                    "enabled": False,
                    "list_of_scripts":  [

                    ]
                },
                "welcome_message": {  # 欢迎进场
                    "enabled": False,
                    "list_of_scripts": [

                    ]
                },
                "keyword_responses": {  # 关键词回复
                    "enabled": False,
                    "list_of_scripts": {

                    }

                }
            },
            "gui_settings": {  # GUI窗口设置
                "window_geometry": "1100x750+0+0",  # 窗口大小
                "selected_tab": 0              # 上次选中标签页
            }
        }
        self.config = self._load_config()  # 加载配置

    def _load_config(self) -> dict:
        """加载配置文件"""
        if os.path.exists(self.config_path):
            try:
                with open(self.config_path, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception as e:
                print(f"加载配置失败: {e}，使用默认配置")
                return self.default_config
        else:
            print("配置文件不存在，使用默认配置")
            return self.default_config

    def save_config(self) -> tuple[bool, str]:
        """保存配置到文件"""
        try:
            with open(self.config_path, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, ensure_ascii=False, indent=2)
            return True, "配置保存成功"
        except Exception as e:
            return False, f"配置保存失败: {str(e)}"

    # ------------------- 发送设置（Property封装，简化调用） -------------------
    @property
    def send_settings(self) -> dict:
        return self.config.get("send_settings", self.default_config["send_settings"])

    @send_settings.setter
    def send_settings(self, value: dict):
        self.config["send_settings"] = value
        self.save_config()

    # ------------------- 监听设置 -------------------
    @property
    def listener_settings(self) -> dict:
        return self.config.get("listener_settings", self.default_config["listener_settings"])

    @listener_settings.setter
    def listener_settings(self, value: dict):
        self.config["listener_settings"] = value
        self.save_config()

    # ------------------- GUI设置 -------------------
    @property
    def gui_settings(self) -> dict:
        return self.config.get("gui_settings", self.default_config["gui_settings"])

    @gui_settings.setter
    def gui_settings(self, value: dict):
        self.config["gui_settings"] = value
        self.save_config()

    # ------------------- 查询设置 -------------------
    @property
    def query_settings(self) -> dict:
        return self.config.get("query_settings", self.default_config["query_settings"])

    @query_settings.setter
    def query_settings(self, value: dict):
        self.config["query_settings"] = value
        self.save_config()

    # ------------------- 综合功能设置 -------------------
    @property
    def comprehensive_settings(self) -> dict:
        return self.config.get("comprehensive_settings", self.default_config["comprehensive_settings"])

    @comprehensive_settings.setter
    def comprehensive_settings(self, value: dict):
        self.config["comprehensive_settings"] = value
        self.save_config()